package thread.day3;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 实现多线程的第三种方式:
 * 自定义类实现Callable接口,然后实现call()方法,
 * 再将对象实例传入FutureTask,生成FutureTask实例,
 * 再把FutureTask实例传给Thread类(FutureTask实现了Future和Runnable接口)
 *这种方式的优势:
 * 1.call()方法有返回值,可以用FutureTask的get()方法回调获取返回值
 *2.call()方法可以抛出异常
 * 3.call()同时也是支持泛型的
 * @author wx
 * @create 2019-11-29 11:38
 */
public class CallableThreadDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        NumThreadDemo numThreadDemo = new NumThreadDemo();

        FutureTask futureTask = new FutureTask(numThreadDemo);
        Thread thread = new Thread(futureTask);
        thread.start();

        Object sum =  futureTask.get();
        System.out.println("sum = " + sum);
    }
}


class NumThreadDemo implements Callable {

    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            if (i % 2 == 0) {
                System.out.println("i = " + i);
                sum+=i;
            }
        }
        return sum;
    }
}